/**
 * @file index.js
 * @author swan
 */
const app = getApp()
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var bdApi = require('../../utils/bdApi.js');
var bdRequest = require('../../utils/bdRequest.js')
import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var WxParse = require('../../wxParse/wxParse.js');
import seoConfig from '../../seoConfig/config.js'
Page({
  data: {
    title: '文章列表',
    postsList: {},
    pagesList: {},
    categoriesList: {},
    postsShowSwiperList: {},
    isLastPage: false,
    page: 1,
    search: '',
    categories: 0,
    specialName: '',
    categoriesImage: "",
    showerror: "none",
    isCategoryPage: "none",
    isSearchPage: "none",
    showallDisplay: "block",
    displaySwiper: "block",
    floatDisplay: "none",
    searchKey: "",
    description: '',
    postsSpecialList: []
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
      this.fetchPostsData(self.data);
    }
    else {
      swan.showToast({
        title: '没有更多内容',
        mask: false,
        duration: 1000
      });
    }
  },
  fetchSpecial() {
   swan.showLoading({
            title: '正在加载',
            mask: true
    });
    var self = this
    var getPostsRequest = bdRequest.getRequest(Api.getSpecial());
    getPostsRequest.then(response => {
      console.log(response, 'getSpecial')
      if (response.statusCode == '200' && response.data.length > 0) {
        let ids = [], urls = [], postUrls = []
        for (let item of response.data) {
          ids.push(item.id)
          // urls.push(bdRequest.getRequest(Api.getSpecialListImg(item.id))) 
          let getImgRequest = bdRequest.getRequest(Api.getSpecialListImg(item.id));
          urls.push(getImgRequest)
          let getPostResquest = bdRequest.getRequest(Api.getSpecialPostList(item.id, 3));
          postUrls.push(getPostResquest)
        }
        Promise.all(urls).then((result) => {
          Promise.all(postUrls).then((result1) => {
            response.data.forEach((item, index, arr) => {
              console.log(result[index].data.data.thumb,result1)
              item.imgurl = result[index].data.data.thumb
              item.postList=result1[index].data
            })
            let arr = []
            response.data.forEach(function (item) {
            //   if (config.getSpecial.includes(item.id)) {
                arr.push(item);
            //   }
            })
            self.setData({
              postsSpecialList: self.data.postsSpecialList.concat(arr),
            });
            swan.hideLoading();
          }).catch((error) => {
            console.log(error)
            swan.hideLoading();
          })
        }).catch((error) => {
          console.log(error)
          swan.hideLoading();
        })
      }
    })
  },
  onLoad: function (options) {
    var self = this;
    this.setData({
      specialName: '档案知识专题'
    })
    this.fetchSpecial()
    
   this.setConfig(seoConfig.specialConfig)  

  },
  setConfig(seo) {
        swan.setPageInfo && swan.setPageInfo(seo)
  },
  //获取文章列表数据
  fetchPostsData: function (data) {
    var self = this;
    if (!data) data = {};
    if (!data.page) data.page = 1;
    if (!data.categories) data.categories = 0;
    if (!data.search) data.search = '';
    if (data.page === 1) {
      self.setData({
        postsList: []
      });
    };

    swan.showLoading({
      title: '正在加载',
      mask: true
    });

    var getPostsRequest = bdRequest.getRequest(Api.getPosts(data));
    getPostsRequest.then(response => {
      if (response.statusCode === 200) {

        //   for (let i = 0; i < response.data.length; i++) {
        //     var rendered = response.data[i].excerpt.rendered;
        //     var res = WxParse.bdParse('rendered', 'html', rendered, self, 5, true);
        //     response.data[i].excerpt.rendered = res;
        //   }
        //     if (response.data.length < pageCount) {
        //         self.setData({
        //             isLastPage: true
        //         });
        //     };
        //     self.setData({
        //         floatDisplay: "block",
        //         showallDisplay: "block",
        //         postsList: self.data.postsList.concat(response.data.map(function (item) {
        //             var strdate = item.date
        //             if (item.category_name != null) {

        //                 item.categoryImage = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/topic.png";
        //             }
        //             else {
        //                 item.categoryImage = "";
        //             }

        //             if (item.post_thumbnail_image == null || item.post_thumbnail_image == '') {
        //                 item.post_thumbnail_image = 'https://www.bds110.com/wp-content/uploads/bdsmp-dacx/logo700.png';
        //             }
        //             item.date = util.cutstr(strdate, 10, 1);
        //             return item;
        //         })),

        //     });



      }
      else {
        if (response.data.code == "rest_post_invalid_page_number") {
          self.setData({
            isLastPage: true
          });

        }
        else {
          swan.showToast({
            title: response.data.message,
            duration: 1500
          })
        }
      }

    })
      .catch(function () {
        if (data.page == 1) {

          self.setData({
            showerror: "block",
            floatDisplay: "none"
          });

        }
        else {
          swan.showModal({
            title: '加载失败',
            content: '加载数据失败,请重试.',
            showCancel: false,
          });
          self.setData({
            page: data.page - 1
          });
        }
      })
      .finally(function () {
        swan.hideLoading();

      })
  },



  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    swan.navigateTo({
      url: url
    })
  },

  //获取分类列表
  fetchCategoriesData: function (id) {
    var self = this;
    self.setData({
      categoriesList: []
    });

    var getCategoryRequest = bdRequest.getRequest(Api.getCategoryByID(id));

    getCategoryRequest.then(response => {

      var catImage = "";
      if (typeof (response.data.category_thumbnail_image) == "undefined" || response.data.category_thumbnail_image == "") {
        catImage = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/website.png";
      }
      else {
        catImage = response.data.category_thumbnail_image;
      }

      self.setData({
        categoriesList: response.data,
        categoriesImage: catImage,
        categoriesName: response.data.name,
        description: response.data.description,

      });

      swan.setNavigationBarTitle({
        title: response.data.name,
        success: function (res) {
          // success
        }
      });

      self.fetchPostsData(self.data);

    })
  },
   redictAppDetail: function (e) {
        console.log('查看文章');
        var id = e.currentTarget.id;
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;

        if (redicttype == 'detailpage')//跳转到内容页
        {
            url = '../detail/detail?id=' + id;
            swan.navigateTo({
                url: url
            })
        }
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }
    }
})
